﻿using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using CYTS.Aoyou.Framework.Config;
using CYTS.Aoyou.Framework.Context;
using CYTS.Aoyou.Framework.Utility;

namespace CYTS.Aoyou.Framework.Service
{
    public class WCFServiceHostFactory : ServiceHostFactory
    {
        static WCFServiceHostFactory()
        {
            string minThreads = System.Configuration.ConfigurationManager.AppSettings["MinThreadsCount"];
            int threadsCount = 0;
            if (string.IsNullOrEmpty(minThreads) || !int.TryParse(minThreads, out threadsCount))
            {
                threadsCount = Environment.ProcessorCount * 2;
            }
            System.Threading.ThreadPool.SetMinThreads(threadsCount, threadsCount);
        }

        /// <summary>
        /// 创建Host (IIS/WAS)
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="baseAddresses"></param>
        /// <returns></returns>
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            ServiceHostConfig config = ConfigFactory.GetConfig<ServiceHostConfig>();
            if (config.WCFServiceHosts == null)
            {
                throw new Exception("配置文件关键元素缺失");
            }

            WCFServiceHost hostConfig = config.WCFServiceHosts.FirstOrDefault(p => p.ServiceName.ToLower() == serviceType.FullName.ToLower());
            if (hostConfig == null)
            {
                throw new Exception("为找到服务对应的配置: " + serviceType.FullName);
            }

            ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
            Type contractType = TypeHelper.GetServiceContractType(serviceType);
            WCFServiceHostPackager.PackageWCFServiceHost(host, contractType, hostConfig.Endpoints);
            //注册服务端上下文句柄
            ContextFactory.RegisterContextHandler(new ServiceContextHandler());

            return host;
        }

        /// <summary>
        /// 创建Host (Console/WinForm/WindowsService)
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        public ServiceHost CreateServiceHost(Type serviceType)
        {
            ServiceHostConfig config = ConfigFactory.GetConfig<ServiceHostConfig>();
            if (config.WCFServiceHosts == null)
            {
                throw new Exception("配置文件关键元素缺失");
            }

            WCFServiceHost hostConfig = config.WCFServiceHosts.FirstOrDefault(p => p.ServiceName.ToLower() == serviceType.FullName.ToLower());
            if (hostConfig == null)
            {
                throw new Exception("为找到服务对应的配置: " + serviceType.FullName);
            }

            ServiceHost host = new ServiceHost(serviceType, new Uri(hostConfig.BaseAddress));
            Type contractType = TypeHelper.GetServiceContractType(serviceType);
            WCFServiceHostPackager.PackageWCFServiceHost(host, contractType, hostConfig.Endpoints);
            //注册服务端上下文句柄
            ContextFactory.RegisterContextHandler(new ServiceContextHandler());

            return host;
        }
    }
}
